//
//  ClubInfoViewController.swift
//  77Club
//
//  Created by Apple on 2024/8/26.
//

import UIKit
import JXSegmentedView
import SnapKit

private let headerID    = "ClubInfoTopCateView"

class ClubInfoViewController: ClubBaseViewController {

    private var titleLabel = c_make_ex(UILabel.self)
        .text("推荐").font(17.font_semiBold).color("#17181A").end()
    private var dianImage = c_make_ex(UIImageView.self)
        .image("Home_tag").mode(.scaleAspectFill).end()
    private let searchButton = UIIconButton(style: .leading(itemSpace: 0))
    private var topView = ClubInfoTopView()
  
    private lazy var tableView: UITableView = {
        let tableView = UITableView()
        tableView.delegate = self
        tableView.dataSource = self
        tableView.backgroundColor = .clear
        tableView.showsVerticalScrollIndicator = false
        tableView.rowHeight = 102.0.Scale
        tableView.register(ClubInfoCell.self)
        tableView.register(ClubInfoTopCateView.self, forHeaderFooterViewReuseIdentifier: headerID)
        tableView.contentInsetAdjustmentBehavior = .never
        tableView.separatorStyle = .none
        return tableView
    }()
    
    var pageIndex = 1
    private var dataSource: [ClubHomeInfoItemModel]?
    private var cateId = ""
    private var cateModels = [ClubHomeNormalGameTypeModel]()
    private var isLoadCateM = true
    
    override func viewDidLoad() {
        super.viewDidLoad()

        loadCateData()
        
        view.subviews{
            titleLabel
            dianImage
            searchButton
            tableView
        }
        
        titleLabel.leading(15.0.Scale).top(.statusHeight+10.0.Scale)
        dianImage.size(13.0.Scale)
        dianImage.CenterX == titleLabel.CenterX
        dianImage.Top == titleLabel.Bottom - 3
        searchButton.trailing(12.0.Scale).top(.statusHeight+8.0.Scale).width(280.0.Scale).height(30.0.Scale)
        tableView.leading(0).top(.navi_height).trailing(0).bottom(0)
        topView.frame = CGRect(x: 0, y: 0, width: .screenWidth, height: 170.0.Scale)
        tableView.tableHeaderView = topView
        
        tableView.refresh_loadMore {
            self.loadMoreData()
        }.refresh_pull {
            self.loadNewData()
        }
 
        searchButton.style { v in
            v.iconSize = CGSize(width: 16.0.Scale, height: 16.0.Scale)
            v.setImage("Info_search".toImage, for: .normal)
            v.setTitle("请输入关键进行搜索", for: .normal)
            v.setTitleColor("#AEB0B3".toColor, for: .normal)
            v.contentEdgeInsets = UIEdgeInsets(top: 7, left: 6, bottom: 0, right: 0)
            v.titleLabel?.font = 12.font_medium
            v.contentHorizontalAlignment = .leading
            v.addTarget(self, action: #selector(searchButtonClick), for: .touchUpInside)
            v.backgroundColor = "#EDEEF0".toColor
            v.layer.cornerRadius = 15.0.Scale
            v.layer.masksToBounds = true
        }
    }
    
    @objc private func searchButtonClick(){
        self.navigationController?.pushViewController(ClubInfoSearchViewController(), animated: true)
    }
}


//MARK: Data
extension ClubInfoViewController {
    
    private func loadCateData(){

        Task{
            let models = await network.request(.infoCate,type: ClubHomeNormalGameTypeModel.self,isShowError: false)
            if models.isSuccess, let models = models.models {

                self.cateId = models[0].id
                var cateArr = [ClubHomeNormalGameTypeModel]()
                for i in 0..<models.count {
                    var md = models[i]
                    if i == 0 {
                        md.isSel = true
                    }else{
                        md.isSel = false
                    }
                    cateArr.append(md)
                }
                self.cateModels = cateArr
                self.loadData()
                self.loadBannersData()
            }
        }
    }
    
    private func loadBannersData(){
        
        Task{
            let models = await network.requestMore(.infolist(class_id: cateId, page: 1,keyword: ""), type: ClubHomeInfoModel.self)
            if models.isSuccess, let model = models.model {
                self.topView.bannarModel = model.banners
            }
        }
    }
    
    private func loadData(){
        ToastUtil.show()
        Task{
            let models = await network.requestMore(.infolist(class_id: cateId, page: pageIndex,keyword: ""), type: ClubHomeInfoModel.self)
            tableView.refresh_end()
            ToastUtil.dismiss()
            if models.isSuccess, let model = models.model {
                self.dataSource = model.data
                tableView.reloadData()
            }
        }
    }
    
    @objc private func loadNewData(){
        pageIndex = 1
        loadData()
    }
    
    @objc private func loadMoreData(){
        pageIndex += 1
        
        Task{
            let models = await network.requestMore(.infolist(class_id: cateId, page: pageIndex,keyword: ""), type: ClubHomeInfoModel.self)
            tableView.refresh_end()
            if models.isSuccess, let model = models.model {
                if let data = model.data, data.count > 0 {
                    for mod in data {
                        self.dataSource?.append(mod)
                    }
                }else{
                    self.tableView.refresh_end(true)
                }
                tableView.reloadData()
            }
        }
    }
}

//MARK: - UITableViewDelegate, UITableViewDataSource
extension ClubInfoViewController: UITableViewDelegate, UITableViewDataSource {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        return dataSource?.count ?? 0
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCell(withIdentifier: "ClubInfoCell", for: indexPath) as! ClubInfoCell
        cell.model = dataSource?[indexPath.row]
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        let model = dataSource?[indexPath.row]
        let webView = ClubWebViewController()
        var urlStr = model?.webview_url ?? ""
        if let uid = UserDefaultsManager.getString(forKey: .uid), uid.count > 0 {
            urlStr = urlStr + "&uid=\(uid)"
        }
        urlStr = urlStr + "&model=ios"
        webView.urlString = urlStr
        webView.titleName = "资讯详情"
        webView.ishiddenNav = true
        self.navigationController?.pushViewController(webView, animated: true)
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        
        return 40.0.Scale
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        
        let header = tableView.dequeueReusableHeaderFooterView(withIdentifier: headerID) as! ClubInfoTopCateView
        if isLoadCateM {
            header.model = cateModels
        }        
        header.updateCateData = { cateID in
            self.isLoadCateM = false
            self.cateId = cateID
            self.loadNewData()
        }
        return header
    }
}
